package com.haohan.cloud.scm.common.tools.util;

import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import lombok.experimental.UtilityClass;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author dy
 * @date 2019/9/13
 */
@UtilityClass
public class ValidatorUtil {

    private Validator validator = Validation.buildDefaultValidatorFactory()
            .getValidator();

    public <T> String validate(T obj) {
        return validate(obj, true);
    }

    /**
     * 实体类属性 验证
     *
     * @param obj
     * @param keyFlag 是否带 属性名
     * @param <T>
     * @return
     */
    public <T> String validate(T obj, boolean keyFlag) {
        Map<String, StringBuilder> errorMap = null;
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (set != null && set.size() > 0) {
            errorMap = new HashMap<String, StringBuilder>(16);
            String property = null;
            for (ConstraintViolation<T> cv : set) {
                //这里循环获取错误信息，可以自定义格式
                property = cv.getPropertyPath().toString();
                if (errorMap.containsKey(property)) {
                    errorMap.get(property).append(",").append(cv.getMessage());
                } else {
                    StringBuilder sb = new StringBuilder();
                    sb.append(cv.getMessage());
                    errorMap.put(property, sb);
                }
            }
        }
        if (errorMap == null) {
            return null;
        }
        StringBuilder msg = new StringBuilder();
        for (Map.Entry<String, StringBuilder> entry : errorMap.entrySet()) {
            if (keyFlag) {
                msg.append(entry.getKey()).append(":");
            }
            msg.append(entry.getValue()).append(";");
        }
        return msg.toString();
    }

    /**
     * 验证必须属性; 失败返回true
     *
     * @param rowInfo
     * @param index
     * @param msg
     * @param <T>
     * @return
     */
    public <T> boolean validateInfo(T rowInfo, int index, StringBuilder msg) {
        // 验证
        String result = validate(rowInfo, false);
        if (null != result) {
            msg.append("第").append(index).append("行填写有误:").append(result).append("|");
            return true;
        }
        return false;
    }

    /**
     * 验证实体类属性 错误时throw
     *
     * @param entity
     */
    public <T> void validateProperty(T entity) {
        String msg = ValidatorUtil.validate(entity, false);
        if (null != msg) {
            throw new ErrorDataException(msg);
        }
    }
}
